<?php

use think\Db;

/**
 * 计算两地之间的距离（根据经纬度）
 * lng1,lng2 经度
 * lat1,lat2 纬度
 * float 距离，单位千米
 */
function getdistance($distance1, $distance2)
{
    //将角度转换为弧度1
    $radLat1 = deg2rad($distance1['lat'] ?? 0);//deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($distance2['lat'] ?? 0);
    $radLng1 = deg2rad($distance1['lng'] ?? 0);
    $radLng2 = deg2rad($distance2['lng'] ?? 0);
    $a       = $radLat1 - $radLat2;
    $b       = $radLng1 - $radLng2;
    return 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
}

/**
 * 获取全局唯一标识符
 * @param bool $trim
 * @return string
 */
function getGuidV4($trim = true)
{
    // Windows
    if (function_exists('com_create_guid') === true) {
        $charid = com_create_guid();
        return $trim == true ? trim($charid, '{}') : $charid;
    }
    // OSX/Linux
    if (function_exists('openssl_random_pseudo_bytes') === true) {
        $data    = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    // Fallback (PHP 4.2+)
    mt_srand((double)microtime() * 10000);
    $charid = strtolower(md5(uniqid(rand(), true)));
    $hyphen = chr(45);                  // "-"
    $lbrace = $trim ? "" : chr(123);    // "{"
    $rbrace = $trim ? "" : chr(125);    // "}"
    $guidv4 = $lbrace .
        substr($charid, 0, 8) . $hyphen .
        substr($charid, 8, 4) . $hyphen .
        substr($charid, 12, 4) . $hyphen .
        substr($charid, 16, 4) . $hyphen .
        substr($charid, 20, 12) .
        $rbrace;
    return $guidv4;
}
//发送请求
function https_request($url,$data,$type){

    if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);

        $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");

        $data=json_encode($data);

    }

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (!empty($data)){

        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS,$data);

    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );

    $output = curl_exec($curl);

    curl_close($curl);

    return $output;

}
//发送请求
function sendCmd($url, $method = 'get', $data = [])
{
//    dump($url);die;
    $curl = curl_init();                                      // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);                    // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);            // 对认证证书来源的检测
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);            // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);            // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);               // 自动设置Referer
    if ($method == 'post') {
        curl_setopt($curl, CURLOPT_POST, 1);           // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);       // 设置超时限制防止死循
    curl_setopt($curl, CURLOPT_HEADER, 0);         // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回


    $tmpInfo = curl_exec($curl); // 执行操作

    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);
    }
    curl_close($curl); // 关键CURL会话
    $tmpInfo = json_decode($tmpInfo, true);
//     dump($tmpInfo);die;
    return $tmpInfo;   // 返回数据
}

function rwm($id)
{
    ob_start();//开启缓冲区
    if (!is_dir('qrcode')) {
        mkdir('qrcode');
    }
    $filename = 'qrcode/' . $id . '.png';
    vendor("phpqrcode.phpqrcode");
    $errorCorrectionLevel = 'H'; //容错级别
    $matrixPointSize      = 10;  //生成图片大小
    $u                    = new \QRcode();
    $QR                   = \QRcode::png('id=' . $id, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    $QR                   = imagecreatefromstring(file_get_contents($filename));
}

function zuzhi($id)
{
    $ids   = [];
    $queue = new \SplQueue();
    $queue->enqueue($id);

    while (!$queue->isEmpty()) {
        $currentId = $queue->dequeue();
        $ids[]     = $currentId;

        // 查询当前节点的直接子节点
        $children = Db::name('zuzhi')
            ->where('pid', $currentId)
            ->where('delete_id', 0)
            ->column('id');

        foreach ($children as $childId) {
            $queue->enqueue($childId);
        }
    }

    return implode(',', $ids);
}

function role($admin)
{
    //查询对应的角色
    $role = Db::name('auth_group_access')
        ->alias('a')
        ->join('auth_group b', 'a.group_id = b.id')
        ->where(['a.uid' => $admin['id']])
        ->value('rules');
    if ($role <> "*") {
        $role = ",{$role},";
    }
    return $role;
}
function zancun($table = 'list_one',$field = 'tong_storage',$prev = "")
{
//    $table = 'list_one';
//    $field = 'tong_storage';
//    $prev  = '';
    //1、获取本商户的最新进货单号
    $newBillNo = db($table)->field($field)->order($field . ' desc')->select();
    //2、拆分获取到的最新单号字符串
    //3、判断时间是否为今天。若是：时间不变，流水号自增；若不是：时间为今日，流水号置00001。
    //获取当前时间的年月日
    $time = date('Ymd', time());
    if ($newBillNo == null) { //无新纪录
        $zancun = $prev . $time . '00001';
    } else { //有记录
        $billno = $newBillNo[0][$field];
        //截取最新单据的时间
        $billTime = substr($billno, strlen($prev), 8);
        if ($billTime != $time) { //是否为今天的第一单
            $zancun = $prev . $time . '00001';
        } else {
            $billWaterNo = substr($billno, strlen($prev) + 8, 5);
            settype($billWaterNo, 'integer'); //将流水号转换成整型
            $billWaterNo++;                   //流水号自增
            //判断流水单号是否为5位
            if ($billWaterNo < 9999){
                $billWaterNo = str_pad($billWaterNo, 5, '0', STR_PAD_LEFT); //左侧填充0至5位
            }
            $zancun = $prev . $time . $billWaterNo;
        }
    }
    return $zancun;
}
function recordChanges($one_id, $xiu) {
    $xiu['yw_join_time'] = date('Y-m-d H:i:s',$xiu['yw_join_time']);
    $xiu['yw_hetong_time'] = date('Y-m-d H:i:s',$xiu['yw_hetong_time']);
    $xiu['yw_shenhe_time'] = date('Y-m-d H:i:s',$xiu['yw_shenhe_time']);
//        $xiu['give_starttime'] = date('Y-m-d H:i:s',$xiu['give_starttime']);
//        $xiu['give_endtime'] = date('Y-m-d H:i:s',$xiu['give_endtime']);
    $xiu['car_register'] = date('Y-m-d H:i:s',$xiu['car_register']);
//        $xiu['car_issue_time'] = date('Y-m-d H:i:s',$xiu['car_issue_time']);
    $xiu['plan_strattime'] = date('Y-m-d',$xiu['plan_strattime']);
    $xiu['plan_endtime'] = date('Y-m-d',$xiu['plan_endtime']);
    $one = db('list_one')->where('id', $one_id)->find();
    $one['yw_join_time'] = date('Y-m-d H:i:s',$one['yw_join_time']);
    $one['yw_hetong_time'] = date('Y-m-d H:i:s',$one['yw_hetong_time']);
    $one['yw_shenhe_time'] = date('Y-m-d H:i:s',$one['yw_shenhe_time']);
//        $one['give_starttime'] = date('Y-m-d H:i:s',$one['give_starttime']);
//        $one['give_endtime'] = date('Y-m-d H:i:s',$one['give_endtime']);
    $one['car_register'] = date('Y-m-d H:i:s',$one['car_register']);
//        $one['car_issue_time'] = date('Y-m-d H:i:s',$one['car_issue_time']);
    $one['plan_strattime'] = date('Y-m-d',$one['plan_strattime']);
    $one['plan_endtime'] = date('Y-m-d',$one['plan_endtime']);
    $changes = array();
    $changes = ['因客户要求，经参统人申请，服务人同意，本服务单'];
    foreach ($one as $k=>$v) {
        if(isset(chuli()[$k])){
            $kname = chuli()[$k];
            if ($kname != null) {
                $v3 = $xiu[$k];
                if($v3!=''){
                    if ($v3 != $v) {
                        $str = (chuli()[$k] ? : $k) . '由 ' . $v . ' 变更为 ' . $v3;
                        array_push($changes, $str);
                    }
                }
            }
        }

    }
    $changes[] = '本服务单其它内容不变，特此批改';
    return implode("\r\n", $changes);
}
function chuli(){
    $dict = [
        'yw_come' => '业务来源',
        'yw_class' => '归属部门',
        'yw_belonger' => '归属人',
        'yw_handle' => '经办',
        'tong_storage' => '参统单暂存号',
        'tong_number' => '服务单号',
//        'tong_document' => '单证号',
        'car_num' => '车牌号',
        'car_is_new' => '是否为新车',
//        'haocolor' => '号牌底色',
        'car_owner' => '车主姓名',
        'car_card_kind' => '证件类型',
        'car_card' => '证件号',
        'car_vin' => '车架号',
        'car_engine' => '发动机号',
        'car_factory_num' => '厂牌型号',
        'car_register' => '注册日期',
        'car_buy' => '新车购置价',
        'car_reall' => '实际价值',
        'car_use_nature' => '使用性质',
        'car_leixing' => '车辆类型',
        'car_carry_peo' => '核定载客',
        'car_carry_quality' => '核定载质量',
        'car_curb_weight' => '整备质量',
        'car_lastyear' => '上年出险情况',
        'plan_strattime' => '服务起期',
        'plan_endtime' => '服务止期',
        'main_name' => '损失服务',
        'main_money' => '损失服务金额',
        'main_standard' => '损失标准服务费',
        'main_discount' => '损失折扣',
        'main_submit' => '损失应交服务费',
        'main_franchise' => '损失不计免赔',
        'main_disan' => '机动车第三者责任服务',
        'main_santong' => '第三者服务金额',
        'main_biao' => '第三者标准服务费',
        'main_zhe' => '第三者折扣',
        'main_yingjiao' => '第三者应交服务费',
        'main_ji' => '第三者不计免赔',
        'dao_name' => '机动车全车盗抢服务',
        'dao_tong' => '盗抢服务金额',
        'dao_biao' => '盗抢标准服务费',
        'dao_zhe' => '盗抢折扣',
        'dao_ying' => '盗抢应交',
        'dao_ji' => '盗抢不计',
        'siji' => '服务司机',
        'siji_tong' => '司机服务',
        'siji_biao' => '司机标准',
        'siji_zhe' => '司机折扣',
        'siji_ying' => '司机应交',
        'siji_ji' => '司机不计',
        'chengke' => '服务乘客',
        'ck_money' => '乘客 元/座',
        'chengke_zuo' => '乘客座',
        'ck_tong' => '乘客服务',
        'ck_biao' => '乘客标准',
        'ck_zhe' => '乘客折扣',
        'ck_ying' => '乘客应交',
        'ck_ji' => '乘客不计',
        'main_sum' => '基准服务费用合计',
        'main_sumdiscount' => '合计折扣',
        'main_free' => '服务费合计',
        'learned_name' => '被参统人姓名',
        'learned_kind' => '被参统人证件类型',
        'learned_num' => '被参统人证件号码',
        'learned_phone' => '被参统人手机号',
        'resolvent' => '解决方式',
        'special' => '特别约定',
        'dianwang' => '外部电网',
        'dw_tong' => '外部电网服务费',
        'dw_biao' => '标准服务费',
        'dw_zhe' => '外部电网折扣',
        'dw_ying' => '外部电网应交',
        'dw_ji' => '外部电网不计',
    ];
    return $dict;
}
function saveOneFile($id, $urls) {
    // 会有重复的可能，需要处理
    $olds = db('tong_files')->where('tong_id', $id)->select();

    $newid = $id;
    $urls = explode(',', $urls);
    $count = count($urls);
    $res = false;
    for ($i=0;$i<$count;$i++){
        $url = $urls[$i];
        $found = false;
        for ($j=0; $j<count($olds); $j++) {
            if ($olds[$j]['url'] == $url) {
                $found = true;
                break;
            }
        }
        if ($found) continue;

        $img['url'] = $urls[$i];
        $img['tong_id'] = $newid;
        $img['title'] = '';
        $img['updatetime'] = time();
        $res = db('tong_files')->insert($img);
    }
    return $res;
}
function genghuan_one($id)
{
    $datares = Db::name('list_three')->where('id', $id)->find();

    $datares['id'] = $datares['ids'];

    if (empty($datares['main_netrate']) && strlen($datares['main_netrate']) == 0) {
        unset($datares['main_netrate']);
    }
    if (empty($datares['main_netcost']) && strlen($datares['main_netcost']) == 0) {
        unset($datares['main_netcost']);
    }
    if (empty($datares['main_tongchoufee_heji']) && strlen($datares['main_tongchoufee_heji']) == 0) {
        unset($datares['main_tongchoufee_heji']);
    }
    if (empty($datares['main_xiaoguan_bili']) && strlen($datares['main_xiaoguan_bili']) == 0) {
        unset($datares['main_xiaoguan_bili']);
    }
    if (empty($datares['main_xiaoguan']) && strlen($datares['main_xiaoguan']) == 0) {
        unset($datares['main_xiaoguan']);
    }
    if (empty($datares['main_yunying_bili']) && strlen($datares['main_yunying_bili']) == 0) {
        unset($datares['main_yunying_bili']);
    }
    if (empty($datares['main_yunying']) && strlen($datares['main_yunying']) == 0) {
        unset($datares['main_yunying']);
    }
    if (empty($datares['main_tongchoujingfee_heji']) && strlen($datares['main_tongchoujingfee_heji']) == 0) {
        unset($datares['main_tongchoujingfee_heji']);
    }
    if (empty($datares['dong_fee']) && strlen($datares['dong_fee']) == 0) {
        unset($datares['dong_fee']);
    }
    //判断status状态
    $batch_state = $datares['batch_state']; //1-退单 2-改单（初审） 3-增单（初审、财务）
    unset($datares['batch_state']);
    unset($datares['status']);
    if ($batch_state == 1) {
        //退
        $datares['status'] = 6;
    }
    Db::name('list_one')->where('id', $datares['id'])->update($datares);
}